<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     Pagizer
 * @subpackage  backoffice
 */

/**
 * Service to manage temporary document stored in 'f_temp' table in db
 */

class m_backoffice_services_TempDocService extends f_core_Service
{
	private static $instance;
	
	/**
	 * @return m_backoffice_services_TempDocService
	 */
	private function __construct()
	{
		return $this;
	}
	
	/**
	 * Get singleton instance
	 *
	 * @return m_backoffice_services_TempDocService
	 */
	public static function getInstance()
	{
		if(self::$instance === null)
		{
			self::$instance = new self();
		}
		return self::$instance;
	}
	
	/**
	 * Check if document is in temporary table
	 * 
	 * @param integer $documentId
	 * @param string $lang
	 * @return boolean
	 */
	public function hasTemporary($documentId, $lang = null)
	{
		$dbProvider = f_database_Provider::getInstance();
		
		if(is_null($lang))
		{
			$lang = $this->getContextLang();	
		}		
				
		$docId = $dbProvider->setQuery("SELECT `document_uid` FROM `f_temp` WHERE `document_uid`=:documentId AND `document_lang`=:lang")
							->execute(array("documentId" => intval($documentId), "lang" => $lang))
							->getQueryResult(PDO::FETCH_COLUMN);
		
		if(is_null($docId))
		{
			return false;
		}
		
		return true;
	}

    /**
     * Retrieve document from temp table if exists else return document from original table
     * @param integer $documentId
     * @param lang $lang
     * @return f_document_BaseDocument
     */
    public function getDocument($documentId, $lang = null)
    {
        if(is_null($lang))
		{
			$lang = $this->getContextLang();
		}

        if($this->hasTemporary($documentId, $lang))
        {
            return $this->getTemporaryDocument($documentId, $lang);
        }
        else
        {
            return f_document_Provider::getInstance()->getByUniqueId($documentId, $lang);
        }
    }

    public function getAllTemporaryDocuments()
    {
 		$dbProvider = f_database_Provider::getInstance();


		$documents = $dbProvider->setQuery("SELECT `document_content` FROM `f_temp`")
                                ->execute()
                                ->getQueryResults(PDO::FETCH_COLUMN);

        $result = array();
		if(is_array($documents) && count($documents) > 0)
        {
            foreach ($documents as $doc)
            {
                $result[] = unserialize($doc);
            }
        }
        return $result;
    }
	
	/**
	 * Retrieve a document stored in temporary table
	 * @return f_document_BaseDocument
	 * @param integer $documentId
	 * @param string $lang[optional]
	 */
	public function getTemporaryDocument($documentId, $lang = null, $returnOriginalIfNull = false)
	{
		$dbProvider = f_database_Provider::getInstance();
		
		if(is_null($lang))
		{
			$lang = $this->getContextLang();	
		}			

		$document = $dbProvider->setQuery("SELECT `document_content` FROM `f_temp` WHERE `document_uid`=:documentId AND `document_lang`=:lang")
							->execute(array("documentId" => $documentId, "lang" => $lang))
							->getQueryResult(PDO::FETCH_COLUMN);
							
		$doc = unserialize($document);

        if($doc !== false)
        {
            return $doc;
        }

        return f_document_Provider::getInstance()->getByUniqueId($documentId, $lang);
	}
	
	/**
	 * Save a document into temporary table
	 * 
	 * @param $document
	 * @return null
	 */
	public function saveTemporaryDocument($document)
	{
		$dbProvider = f_database_Provider::getInstance();

        $document->setModificationDate(f_date_Date::getInstance()->toString());

		if($this->hasTemporary($document->getUniqueId(), $document->getLang()))
		{
			$dbProvider	->setQuery("UPDATE `f_temp` SET `document_content`=:docContent WHERE `document_uid`=:docId AND `document_lang`=:lang")
						->execute(array("docId" => $document->getUniqueId(), "lang" => $document->getLang(), "docContent" => serialize($document)));						
		}
		else
		{
			$dbProvider	->setQuery("INSERT INTO `f_temp` (`document_uid`, `document_lang`, `document_content`) VALUES (:docId, :lang, :docContent)")
						->execute(array("docId" => $document->getUniqueId(), "lang" => $document->getLang(), "docContent" => serialize($document)));
		}
	}

	/**
	 * Delete a document stored into temporary table
	 * @param $documentId
	 * @param $lang
	 * @return unknown_type
	 */
	public function deleteTempDocument($documentId, $lang = null)
	{
		$dbProvider = f_database_Provider::getInstance();
		
		if(is_null($lang))
		{
			$lang = $this->getContextLang();	
		}	
		
		$dbProvider->setQuery("DELETE FROM `f_temp` WHERE `document_uid`=:documentId AND `document_lang`=:lang" )
					->execute(array("documentId" => $documentId, "lang" => $lang));
	}
}